package com.lingyu.jsjx.service.impl;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanValidators;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteDeptService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lingyu.jsjx.mapper.CoursePlanMapper;
import com.lingyu.jsjx.domain.CoursePlan;
import com.lingyu.jsjx.service.ICoursePlanService;

import javax.validation.Validator;


/**
 * 教学规划
 * Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-31
 */
@Service
public class CoursePlanServiceImpl extends ServiceImpl<CoursePlanMapper, CoursePlan> implements ICoursePlanService {
    @Autowired
    private CoursePlanMapper coursePlanMapper;
    @Autowired
    private RemoteDeptService deptService;
    @Autowired
    private Validator validator;

    /**
     * 查询教学规划
     *
     * @param planId 教学规划
     *               主键
     * @return 教学规划
     */
    @Override
    public CoursePlan selectCoursePlanByPlanId(Long planId) {
        return coursePlanMapper.selectCoursePlanByPlanId(planId);
    }

    /**
     * 查询教学规划
     * 列表
     *
     * @param coursePlan 教学规划
     * @return 教学规划
     */
    @Override
    @DataScope(deptAlias = "u", userAlias = "cp", type = "jsjx")
    public List<CoursePlan> selectCoursePlanList(CoursePlan coursePlan) {
        coursePlan.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        return coursePlanMapper.selectCoursePlanList(coursePlan);
    }

    /**
     * 新增教学规划
     *
     * @param coursePlan 教学规划
     * @return 结果
     */
    @Override
    public int insertCoursePlan(CoursePlan coursePlan) {
        coursePlan.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(coursePlan);
    }

    /**
     * 修改教学规划
     *
     * @param coursePlan 教学规划
     * @return 结果
     */
    @Override
    public int updateCoursePlan(CoursePlan coursePlan) {
        return baseMapper.updateById(coursePlan);
    }

    /**
     * 批量删除教学规划
     *
     * @param planIds 需要删除的教学规划
     *                主键
     * @return 结果
     */
    @Override
    public int deleteCoursePlanByPlanIds(Long[] planIds) {
        return coursePlanMapper.deleteCoursePlanByPlanIds(planIds);
    }

    /**
     * 删除教学规划
     * 信息
     *
     * @param planId 教学规划
     *               主键
     * @return 结果
     */
    @Override
    public int deleteCoursePlanByPlanId(Long planId) {
        return baseMapper.deleteById(planId);
    }

    /**
     * 统计课程状态数量
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> selectCourseStatusCount() {
        return coursePlanMapper.selectCourseStatusCount();
    }


    @Override
    public String importCoursePlan(List<CoursePlan> coursePlanList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(coursePlanList) || coursePlanList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (CoursePlan coursePlan : coursePlanList) {
            try {
                SysDept dept1 = deptService.selectDeptByName(coursePlan.getCollageName(), 0L, SecurityConstants.INNER).getData();
                SysDept dept2 = null;
                SysDept dept3 = null;

                if (dept1 != null)
                    dept2 = deptService.selectDeptByName(coursePlan.getMajorName(), dept1.getDeptId(), SecurityConstants.INNER).getData();
                if (dept2 != null)
                    dept3 = deptService.selectDeptByName(coursePlan.getClazzName(), dept2.getDeptId(), SecurityConstants.INNER).getData();
                if (dept1 != null) {
                    coursePlan.setCollageId(dept1.getDeptId());
                }
                if (dept2 != null) {
                    coursePlan.setMajorId(dept2.getDeptId());
                }

                if (dept3 != null) {
                    coursePlan.setClazzId(dept3.getDeptId());
                }

                // 验证数据合法性
                BeanValidators.validateWithException(validator, coursePlan);

                // 检查用户是否已存在
//                CoursePlan existUser = coursePlanMapper.selectUserByUserName(coursePlan.getUserName());
//                if (existUser == null) {

                coursePlan.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
                coursePlan.setCreateByName(SecurityUtils.getUsername());
                coursePlan.setCreateTime(DateUtils.getNowDate());

                coursePlanMapper.insert(coursePlan);
                successNum++;

                successMsg.append("<br/>" + successNum + "、课程 " + coursePlan.getCourseName() + " 导入成功");
//                }
//                else if (isUpdateSupport) {
//                    // 更新已存在用户数据
//                    coursePlan.setUpdateBy(operName);
//                    userMapper.updateUser(coursePlan);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + coursePlan.getUserName() + " 更新成功");
//                } else {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、账号 " + coursePlan.getUserName() + " 已存在");
//                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、课程 " + coursePlan.getCourseName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }
}
